package com.rest.impl;

import java.util.Map;

import com.api.client.OAuthSigner;
import com.api.client.impl.ApiScribeRequest;
import com.api.client.impl.RequestLogger;
import com.api.client.model.ApiResponse;
import com.api.enums.ApiVerb;
import com.api.model.ApiConsumer;
import com.api.model.ApiEnvironment;
import com.api.model.ApiServiceMethod;
import com.api.model.ApiUser;
import com.rest.ApiClientRequest;
import com.rest.ApiServiceResponse;
import com.rest.RequestService;

public class RequestServiceImpl implements RequestService {

	@Override
	public ApiServiceResponse request(ApiClientRequest clientRequest) {

		ApiServiceMethod service = clientRequest.getService();
		ApiEnvironment environment = clientRequest.getEnvironment();
		String path = environment.getScheme() + "://" + environment.getHost() + service.getPath();
		ApiVerb verb = service.getVerb();

		ApiScribeRequest request = new ApiScribeRequest(verb.name(), path);
		Map<String, String> parameters = clientRequest.getValues();
		if (parameters != null) {
			if (verb == ApiVerb.POST) {
				request.addFormValues(parameters);
			} else {
				request.addQueryValues(parameters);
			}
		}

		ApiConsumer consumer = environment.getConsumer();
		OAuthSigner signer = new OAuthSigner(consumer.getKey(), consumer.getSecret());
		ApiUser user = clientRequest.getUser();
		request.sign(signer, user.getAccessKey(), user.getAccessSecret());

		RequestLogger.logRequest(request);

		ApiResponse response = request.send();
		RequestLogger.logResponse(response);

		return new ApiServiceResponse(response.getCode(), response.getBody());
	}
}
